package cn.edu.scau.serviceImpl;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import cn.edu.scau.dao.AccountDao;
import cn.edu.scau.daoImpl.AccountDaoImpl;
import cn.edu.scau.entity.Account;
import cn.edu.scau.entity.Work;
import cn.edu.scau.service.AccountService;

/**
 * 账号服务接口实例
 * @author Administrator
 * 
 *
 */
@Service("accountServiceImpl")
public class AccountServiceImpl implements AccountService {

	//账号Dao实例
	@Resource(name="accountDaoImpl")
	private AccountDao accountDao;
	
	
	public AccountDao getAccountDao() {
		return accountDao;
	}

	public void setAccountDao(AccountDao accountDao) {
		this.accountDao = accountDao;
	}
	
	/**
	 * 注册账号
	 * @param account 封装好的账号类，该类为待检验的账号
	 * @return 注册是否成功,成功并且保存。
	 */
	public boolean registerTheAccount(Account account) {
		
		List<Account> accounts = accountDao.findAll(Account.class);
		
		if(accounts.isEmpty()||accounts==null){
			String newPassword = MD5(account.getPassword());
			account.setPassword(newPassword);
			accountDao.save(account);
			return true;
		}else{
			for(int i=0;i<accounts.size();i++){
				if(accounts.get(i).getName().equals(account.getName())){
					return false;
				}
			}
			String newPassword = MD5(account.getPassword());
			account.setPassword(newPassword);
			accountDao.save(account);
			return true;
		}
	}

	/**
	 * 更新账号信息
	 * @param newAccount 该账号类为更改后信息的账号类
	 * @param id 需要修改账号信息的账号的id
	 */
	public boolean updateTheAccount(Account newAccount,Integer id) {
		
		Account account = accountDao.find(Account.class,id);
		if(account==null){
			return false;
		}else{
			if(newAccount.getName()!=null){
				account.setName(newAccount.getName());
			}
			if(newAccount.getPassword()!=null){
				account.setPassword(MD5(newAccount.getPassword()));
			}
			if(newAccount.getRole()!=null){
				account.setRole(newAccount.getRole());
			}
			accountDao.update(account);
			return true;
		}
		
	}

	/**
	 * 删除账号
	 * @param id 需要删除账号的id
	 */
	public boolean deleteTheAccount(Integer id) {
		Account account = accountDao.find(Account.class, id);
		if(account==null){
			return false;
		}else{
			accountDao.delete(Account.class, id);
			return true;
		}
	}

	/**
	 * 对密码进行MD5加密
	 * @param password 密码
	 * @return 加密后的密码
	 */
	public String MD5(String password) {
		
		byte[] result = null;  
        
		try {  
            MessageDigest md = MessageDigest.getInstance("MD5");  
            md.reset();  
            md.update(password.getBytes("UTF-8"));  
            result = md.digest();  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        
		byte[] data = result;  
		  
        StringBuffer hexString = new StringBuffer();  
        for (int i = 0; i < data.length; i++) {  
            String hex = Integer.toHexString(0xff & data[i]);  
              
            if (hex.length() == 1) {  
                hexString.append('0');  
            }  
              
            hexString.append(hex);  
        }  
          
        return hexString.toString();
	}
	
	/**
	 * 登录
	 * @param loginName 账号
	 * @param loginPassword 密码
	 * @param picCode 正确的验证码,controller通过session获得
	 * @param checkCode 用户输入的验证码  
	 * @return 不同的登录检验状态
	 */
	public String loginTheAccount(String loginName,String loginPassword,String picCode,String checkCode) {
		
		List<Account> accounts = accountDao.findAll(Account.class);
	if(checkPicCode(picCode,checkCode)){
		if(accounts.isEmpty()||accounts==null){
			return "用户名或密码不正确!";
		}else{
			for(int i=0;i<accounts.size();i++){
				if((loginName.equals(accounts.get(i).getName()))
						&&(MD5(loginPassword).equals(accounts.get(i).getPassword()))){
					return "登录成功";
				}
			}
			return "用户名或密码不正确!";
		}
	}else{
			return "验证码输入错误!";
	}
}

	/**
	 * 展示个人账户的信息
	 * @param id 账户的id
	 * @return
	 */
	@Override
	public Account showTheAccountById(Integer id) {
		return accountDao.find(Account.class, id);
	}
	
	/**
	 * 展示所有的用户
	 */
	public List<Account> showAllAccount() {
		return accountDao.findAll(Account.class);
	}
	
	/**
	 * 生成验证码
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @throws IOException 
	 */
	@Override
	public void picCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
		BufferedImage bi = new BufferedImage(120, 22, BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.getGraphics();
		Color c = new Color(192, 192,192);
		g.setColor(c);
		g.fillRect(0, 0, 120, 22);
		char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
		Random random = new Random();
		int length = ch.length;
		int index;
		StringBuffer sb  = new StringBuffer();
		for(int i=0;i<6;i++){
			index = random.nextInt(length);
			g.setColor(new Color(random.nextInt(88),random.nextInt(188),random.nextInt(255)));
			g.drawString(ch[index]+"",i*15+10, 18);
			sb.append(ch[index]);
		}
		httpServletRequest.getSession().setAttribute("picCode",sb.toString());
		ImageIO.write(bi,"JPG",httpServletResponse.getOutputStream());
	}
	/**
	 * 检验验证码是否输入正确
	 * @param picCode 正确的验证码 ,通过session获得
	 * @param checkCode 用户输入的验证码
	 * @return 是否正确
	 */
	@Override
	public boolean checkPicCode(String picCode, String checkCode) {
		
		String upperCaseCheckCode = checkCode.toUpperCase();
		if(upperCaseCheckCode.equals(picCode)){
			return true;
		}else{
			return false;
		}
	}
	
}
